package com.qingzhu.controller.userserver;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.DefalutUrl;
import com.qingzhu.pojo.User;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.UserService;
import com.qingzhu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

// 配置该注解为了实现图片的上传
@MultipartConfig(
        /* 1MB=1024KB(即：1兆字节=1024千字节)
           1KB=1024Byte(即：1千字节=1024字节)
           1Byte=8bit(即：1字节=8位)
           =API= location属性，设置文件上传的默认地址 */
        maxFileSize=1024*1024*5,        // 限制上传文件的大小。1024*1024表示1mb(兆)，默认-1表示无限大小
        maxRequestSize=1024*1024*5*5,   // 设置上传请求中,数据的总大小限制,单位: 字节
        fileSizeThreshold=1024*1024     // 如果文件的大小超过指定的阈值，文件将会被写出到磁盘,单位: 字节
)
@WebServlet("/user/update")
public class UserUpdateController extends HttpServlet implements DefalutUrl {
    ObjectMapper objectMapper = new ObjectMapper();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("用户信息修改服务..");
        // 接收浏览器发送过来的文件上传域
        Part part = req.getPart("file");
        // 获取请求头中携带的用户信息
        String userJson = req.getHeader("user");
        userJson = URLDecoder.decode(userJson,"UTF-8");   // 解码
        User user = objectMapper.readValue(userJson, User.class);
        // 上传头像
        int uploadResult = uploadHeadPortrait(part);
        // 修改用户的基本信息
        int i = userService.updateById(user);
        ResultVo resultVo = i>0 ? new ResultVo(200,"修改成功！"):new ResultVo(500,"修改失败！");
        resp.getWriter().write(objectMapper.writeValueAsString(resultVo));
    }


    // 上传头像
    private int uploadHeadPortrait (Part part) throws IOException {
        // 获取头像名称
        String photoName = part.getSubmittedFileName();
        if (photoName != null) {
            InputStream inputStream = part.getInputStream();
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream, photoName);
            Map<String, Object> map = new HashMap<>();
            map.put("myfile", inputStreamResource);
            HttpUtil.post(HFSURL+"/qingzhu_logo/", map);
        }
        return 1;
    }
}
